package com.spider.im.user.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spider.im.common.annotation.RedisLock;
import com.spider.im.common.aspect.BusinessException;
import com.spider.im.common.constant.RespCodeEnum;
import com.spider.im.common.utils.EncryptionUtils;
import com.spider.im.user.entity.User;
import com.spider.im.user.mapper.UserMapper;
import com.spider.im.user.req.UserReq;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spider.im.user.resp.UserResp;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author joy
 * @since 2025-04-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private EncryptionUtils encryptionUtils;

    @RedisLock(keys = {"#userReq.phone"})
    @Override
    public UserResp registerPhone(UserReq userReq) {
        User user = new User();

        BeanUtil.copyProperties(userReq, user);
        if (StrUtil.isNotBlank(user.getPhone())) {
            //判断手机是否加密没加密的话加密，使用正则判断
            if (user.getPhone().matches("^\\d{11}$")) {
                user.setPhone(encryptionUtils.encrypt(user.getPhone()));
            }
        }
        Long count = userMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getPhone, user.getPhone()));
        //判断用户名是否存在，如果存在跑出异常提示用户名已存在
        if (count > 0) {
            throw new BusinessException(RespCodeEnum.USER_EXIST);
        }
        userMapper.insert(user);
        UserResp userResp = new UserResp();
        BeanUtil.copyProperties(user, userResp);
        return userResp;
    }


    @RedisLock(keys = {"#userReq.username"})
    @Override
    public UserResp register(UserReq userReq) {
        User user = new User();

        BeanUtil.copyProperties(userReq, user);
        if (StrUtil.isBlank(user.getPassword())) {
           throw new BusinessException(RespCodeEnum.PASSWORD_NOT_NULL);
        }
        user.setPassword(encryptionUtils.encrypt(user.getPassword()));
        Long count = userMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        //判断用户名是否存在，如果存在跑出异常提示用户名已存在
        if (count > 0) {
            throw new BusinessException(RespCodeEnum.USER_EXIST);
        }
        userMapper.insert(user);
        UserResp userResp = new UserResp();
        BeanUtil.copyProperties(user, userResp);
        return userResp;
    }
}
